//
//  CZTextView.swift
//  CZVVeiBo
//
//  Created by smile on 2017/8/5.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit

class CZTextView: UITextView {
    // 重写font属性监听font变化给占位文字设置字体大小
    override var font: UIFont?{
        didSet{
            placeholderLabel.font = font
        }
    }
    
    // 供外界动态的设置占位 
    var placeholder: String?{
        didSet{
            placeholderLabel.text = placeholder
        }
    }
    
//    var placeholderColor: UIColor?{
//        didSet{
//            placeholderLabel.textColor =
//        }
//    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        backgroundColor = UIColor.white
//        let txt = UITextField()
//        txt.placeholder = ""
        addSubview(placeholderLabel)
        placeholderLabel.snp.makeConstraints { (make) in
            make.left.equalTo(5)
            make.top.equalTo(8)
            make.width.equalTo(CZSCREENW - 10)
        }
        
        // 通知-> 注册系统的通知
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
    }
    
    // 监听文字改变
    @objc private func textDidChange(){
        placeholderLabel.isHidden = self.hasText
    }
    // MARK: - 懒加载控件
    // 占位文字
    private lazy var placeholderLabel: UILabel = {
        let lab = UILabel()
        lab.textColor = UIColor.lightGray
        lab.numberOfLines = 0
        lab.font = self.font
        return lab
    }()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

